/*
 * @features: 功能
 * @description: 说明
 * @Date: 2021-12-31 00:57:57
 * @Author: judu233(769471424@qq.com)
 * @LastEditTime: 2022-08-14 14:03:33
 * @LastEditors: judu233
 */

import { ExtendsLoad } from "../CCExtends";

/**扩展原型组件 */
@ExtendsLoad(cc.Texture2D)
export class Texture2DBaseExtends {

}
/**扩展组件实例方法 */
@ExtendsLoad(cc.Texture2D.prototype)
export class Texture2DExtends {
    /**
     * 获取纹理中指定像素的颜色，原点为左上角，从像素 (1, 1) 开始。
     * @param texture 纹理
     * @param x x 坐标
     * @param y y 坐标
     * @example
     * 获取纹理左上角第一个像素的颜色
     * const color = ImageUtil.getPixelColor(texture, 1, 1);
     * cc.color(50, 100, 123, 255);
     */
    static getPixelColor(texture: cc.Texture2D, x: number, y: number): cc.Color {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = texture.width;
        canvas.height = texture.height;
        const image = texture.getHtmlElementObj();
        ctx.drawImage(image, 0, 0, texture.width, texture.height);
        const imageData = ctx.getImageData(0, 0, texture.width, texture.height);
        const pixelIndex = ((y - 1) * texture.width * 4) + (x - 1) * 4;
        const pixelData = imageData.data.slice(pixelIndex, pixelIndex + 4);
        const color = cc.color(pixelData[0], pixelData[1], pixelData[2], pixelData[3]);
        image.remove();
        canvas.remove();
        return color;
    }
}